import asyncio
import os
import sys

from utils.httpClient import HttpClient

HERO_LIST_URL = "https://game.gtimg.cn/images/lgamem/act/lrlib/js/heroList/hero_list.js"

HERO_SKINS_URL = "https://game.gtimg.cn/images/lgamem/act/lrlib/js/skins/skins.js"

BASE_IMAGE_PATH = "images/英雄联盟手游"

hc = HttpClient()

async def save_hero(hero_name, name, skin_poster):
    print(hero_name, name, skin_poster)
    if not skin_poster: return
    image = await hc.get(skin_poster, parse_json=False)
    name = name.replace('/', '-')
    path = f"{BASE_IMAGE_PATH}/{hero_name}"
    if not os.path.exists(path):
        os.makedirs(path)
    with open(f"{path}/{name}.jpg", 'wb') as f:
        f.write(image)


async def fetch_hero_list():
    hero_list = await hc.get(HERO_LIST_URL)
    heros = hero_list.get("heroList")
    hero_skins = await hc.get(HERO_SKINS_URL)
    skin_list = hero_skins.get("skinList")
    for skinId, skin in skin_list.items():
        heroId = skin.get('heroId')
        hero_info = heros.get(heroId)
        hero_name = hero_info.get("name")
        skin_poster = skin.get('poster')
        skin_name = skin.get("name")
        await save_hero(hero_name, skin_name, skin_poster)


async def main():
    await fetch_hero_list()
    await hc.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())